package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;


    //新增套餐功能
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info("setmeal:{}", setmealDto);
        setmealService.saveWithDish(setmealDto);
        return R.success("套餐添加成功！");

    }
    /**
     * 根据条件查询套餐数据
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    /**
     * Cacheable：在方法执行前spring先查看缓存中是否有数据，如果有数据，则直接返回缓存数据；若没有数据，调用方法并将方法返回值放到缓存中
     * value：缓存的名称，每个缓存名称下面可以有多个key
     * key：缓存的key
     */
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal){
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() !=null,Setmeal::getCategoryId,setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus()!=null,Setmeal::getStatus,setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> list = setmealService.list(queryWrapper);
        return R.success(list);
    }

    //套餐分页查询
    @GetMapping("/page")
    public R<Page<SetmealDto>> page(int page, int pageSize, String name) {
        //构造分页构造器
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>();
        //构造条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件
        if (name != null) {
            queryWrapper.like(Setmeal::getName,name);
        }
        //添加排序条件
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(setmealPage, queryWrapper);
        //查询出page对象，拷贝基本信息给dto
        BeanUtils.copyProperties(setmealPage,setmealDtoPage,"records");
        //获取records
        List<Setmeal> records = setmealPage.getRecords();
        List<SetmealDto> list = records.stream().map((item)->{
            SetmealDto setmealDto = new SetmealDto();
            //对象拷贝
            BeanUtils.copyProperties(item,setmealDto);
            Long categoryId = item.getCategoryId();
            //获取分类对象
            Category category = categoryService.getById(categoryId);
            //获取分类的名称
            String categoryName = category.getName();
            //给分类名称赋值
            setmealDto.setCategoryName(categoryName);
            //返回setmealDto对象
            return setmealDto;
        }).collect(Collectors.toList());
        //给dto page的对象设置records属性
        setmealDtoPage.setRecords(list);
        return R.success(setmealDtoPage);

    }
    //删除套餐(删除套餐基本信息，删除套餐下的菜品)
    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> remove(@RequestParam List<Long> ids){
        log.info("ids:{}",ids);
        setmealService.removeWithSetmealDish(ids);
        return R.success("删除成功！");
    }
    //回显修改套餐的编辑框
    @GetMapping("/{id}")
    //页面需要回显基本信息，套餐下的菜品以及分类名称
    public R<SetmealDto> getById(@PathVariable Long id){
        log.info("id:{}",id);
        SetmealDto setmealDto = setmealService.getWithSetmealDish(id);
        return R.success(setmealDto);

    }
    //修改套餐功能
    @PutMapping
    public R<String> updateWithSetmeal(@RequestBody SetmealDto setmealDto){
        log.info("setmealDto:{}",setmealDto);
        setmealService.updateWithSetmeal(setmealDto);
        return R.success("修改套餐成功");
    }
    //批量停售起售（包括单个）
    @PostMapping("/status/{status}")
    public R<String> updateWithStatus(@PathVariable Integer status,@RequestParam List<Long> ids){
        log.info("status:{}",status);
        Setmeal setmeal = new Setmeal();
        setmeal.setStatus(status);
        for (Long id : ids) {
            setmeal.setId(id);
            setmealService.updateById(setmeal);
        }

        return R.success("套餐状态修改成功");
    }

}
